<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区域 -->
    <el-card class="box-card">
      <!-- 搜索添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容"
                    v-model="queryInfo.query"
                    clearable
                    @clear="getUserList">
            <el-button slot="append"
                       icon="el-icon-search"
                       @click="getUserList">
            </el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary"
                     @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList"
                border
                stripe
                style="width: 100%">
        <el-table-column type="index">
        </el-table-column>
        <el-table-column prop="username"
                         label="姓名"
                         width="180">
        </el-table-column>
        <el-table-column prop="email"
                         label="邮箱">
        </el-table-column>
        <el-table-column prop="mobile"
                         label="电话">
        </el-table-column>
        <el-table-column prop="role_name"
                         label="角色"
                         width="180">
        </el-table-column>
        <el-table-column label="状态"
                         width="180">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state"
                       @change="userStateChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         width="200">
          <template slot-scope="scope">
            <el-tooltip class="item"
                        effect="dark"
                        content="编辑"
                        placement="top"
                        :enterable="false">
              <el-button type="primary"
                         icon="el-icon-edit"
                         size="mini"
                         @click="eidtUsers(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip class="item"
                        effect="dark"
                        content="删除"
                        placement="top"
                        :enterable="false">
              <el-button type="danger"
                         icon="el-icon-delete"
                         size="mini"
                         @click="deleteUser(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item"
                        effect="dark"
                        content="分配"
                        placement="top"
                        :enterable="false">
              <el-button type="warning"
                         icon="el-icon-setting"
                         size="mini"
                         @click="activeRolesDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--分页模块-->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryInfo.pagenum"
                     :page-sizes="[1, 2, 6, 10]"
                     :page-size="queryInfo.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户"
               :visible.sync="dialogVisible"
               width="30%"
               @close="addDialogClose">
      <!-- 内容的主体区域 -->
      <el-form :model="addFrom"
               :rules="addFromRules"
               ref="addFromRef"
               label-width="70px">
        <el-form-item label="用户名"
                      prop="username">
          <el-input v-model="addFrom.username"></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input type="password"
                    v-model="addFrom.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input type="email"
                    v-model="addFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机"
                      prop="mobile">
          <el-input v-model="addFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <el-dialog title="修改信息"
               :visible.sync="editUserVisible"
               width="50%"
               @close="eidtDialogClose">
      <el-form :model="eidtForm"
               :rules="addFromRules"
               ref="eidtFormRef"
               label-width="70px">
        <el-form-item label="用户名"
                      prop="username">
          <el-input v-model="eidtForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input type="email"
                    v-model="eidtForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机"
                      prop="mobile">
          <el-input v-model="eidtForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editUserVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editUser(eidtForm)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色"
               :visible.sync="rolesDialogVisible"
               width="50%"
               @close="rolesDialogClose">
      <p>当前的用户: {{rolesInfo.username}}</p>
      <p>当前的角色: {{rolesInfo.role_name}}</p>
      <!-- 下拉选择角色 -->
      <span>分配新角色:
        <el-select v-model="checkRoleID"
                   placeholder="请选择">
          <el-option v-for="item in allRoleList"
                     :key="item.id"
                     :label="item.roleName"
                     :value="item.id">
          </el-option>
        </el-select>
      </span>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="rolesDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="setRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (!regEmail.test(value)) return callback(new Error('请输入正确邮箱'))
      callback()
    }
    var checkMobile = (rule, value, callback) => {
      const regEmail = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (!regEmail.test(value)) return callback(new Error('请输入正确手机号'))
      callback()
    }
    return {
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 当前每页显示多少条
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      dialogVisible: false,
      // 控制修改用户对话框的显示与隐藏
      editUserVisible: false,
      // 控制分配角色对话框的显示与隐藏
      rolesDialogVisible: false,
      // 添加用户的表单数据
      addFrom: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFromRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名的长度在3-10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 10, message: '密码的长度在5-10个字符之间', trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 查询到的用户信息对象
      eidtForm: {},
      // 当前点击用户的信息
      rolesInfo: {},
      // 所有的角色列表
      allRoleList: [],
      // 选中的角色ID
      checkRoleID: ''
    }
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听 pagesize 改变的事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值改变的事件
    handleCurrentChange (newCurrent) {
      this.queryInfo.pagenum = newCurrent
      this.getUserList()
    },
    // 监听 switch 开关状态的改变
    async userStateChanged (userinfo) {
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('更新数据成功')
    },
    // 监听添加用户对话框的关闭事件
    addDialogClose () {
      this.$refs.addFromRef.resetFields()
    },
    // 点击确任按钮,添加新用户
    addUser () {
      this.$refs.addFromRef.validate(async valid => {
        if (!valid) return ''
        const { data: res } = await this.$http.post('users', this.addFrom)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.dialogVisible = false
        this.getUserList()
      })
    },
    // 点击修改用户信息
    async eidtUsers (row) {
      this.editUserVisible = !this.editUserVisible
      const { data: res } = await this.$http.get('users/' + row.id)
      if (res.meta.status !== 200) return this.$message.error('获取用户信息失败')
      this.eidtForm = res.data
    },
    // 监听修改用户对话框的关闭
    eidtDialogClose () {
      this.$refs.eidtFormRef.resetFields()
    },
    // 提交修改的内容
    async editUser (eidtForm) {
      this.$refs.eidtFormRef.validate(async valid => {
        if (!valid) return ''
        // 提交
        const { data: res } = await this.$http.put('users/' + eidtForm.id, {
          email: eidtForm.email,
          mobile: eidtForm.mobile
        })
        // 验证返回信息
        if (res.meta.status !== 200) return this.$message.error('修改用户信息失败')
        this.$message.success('修改用户信息成功')
        this.editUserVisible = !this.editUserVisible
        this.getUserList()
      })
    },
    // 删除用户信息
    async deleteUser (id) {
      const i = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (i === 'cancel') {
        this.$message.info('已取消删除')
      }
      if (i === 'confirm') {
        const { data: res } = await this.$http.delete('users/' + id)
        console.log(res)

        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.getUserList()
      }
    },
    // 监听分配角色对话框的关闭
    rolesDialogClose () {
      this.value = ''
    },
    // 点击分配角色对话框
    activeRolesDialog (roles) {
      this.getRoleList()
      this.rolesDialogVisible = true

      this.rolesInfo = roles
      console.log(this.checkRoleID)
    },
    // 获取所有的角色列表
    async getRoleList () {
      const { data: res } = await this.$http.get('roles')
      this.allRoleList = res.data
    },
    async setRoles () {
      // var checkRoleID = this.checkRoleID
      const { data: res } = await this.$http.put(`users/${this.rolesInfo.id}/role`, { rid: this.checkRoleID })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('修改角色失败')
      this.getUserList()
      this.$message.success('修改角色成功')
      this.rolesDialogVisible = false
    }

  },
  created () {
    this.getUserList()
  }
}
</script>

<style lang="less" scoped>
.el-breadcrumb {
  font-size: 14px;
  margin-bottom: 20px;
}
.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.3) !important;
}
.el-table {
  margin-top: 20px;
}
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
